﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;

namespace HRZoneTrainer
{
    public partial class SelectSerialPort : Form
    {
        public SelectSerialPort()
        {
            InitializeComponent();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            
        }

        private void SelectSerialPort_Load(object sender, EventArgs e)
        {
            comboBoxSerialPorts.Items.AddRange(SerialPorts);
            comboBoxSerialPorts.SelectedItem = DefaultPort;
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {
            ManagementObjectSearcher deviceList =
                new ManagementObjectSearcher("Select Service, Name from Win32_PnPEntity");

            bool found = false;

            // Any results? There should be!
            if ( deviceList != null )
            {
                // Enumerate the devices
                foreach ( ManagementObject device in deviceList.Get() )
                {
                    if ( ( device.GetPropertyValue("Service") != null ) &&
                        ( device.GetPropertyValue("Name") != null ) )
                    {
                        // To make the example more simple,
                        string name = device.GetPropertyValue("Name").ToString();
                        string service = device.GetPropertyValue("Service").ToString();

                        if ( service == "FTSER2K" )
                        {
                            int nIndex = name.IndexOf("(COM");

                            int commport = Int32.Parse(name.Substring(nIndex + 4, 1));

                            MessageBox.Show("Found device on COM" + commport, "Device found", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            comboBoxSerialPorts.SelectedItem = "COM" + commport;

                            found = true;

                            break;
                        }
                    }
                }
            }

            if ( found == false )
            {
                MessageBox.Show("Device not found", "Device not found", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public string[] SerialPorts { get; set; }
        public string DefaultPort { get; set; }

        public string SelectedSerialPort
        {
            get
            {
                return ( (string) comboBoxSerialPorts.SelectedItem );
            }
        }
    }
}
